"""任务队列管理"""

import asyncio
from collections import deque
from datetime import datetime
from typing import Deque, List, Optional, Dict, Any

from .task import TranscodeTask, TaskStatus


class TaskQueue:
    """任务队列类"""
    
    def __init__(self, max_concurrent_tasks: int = 3):
        self.pending_queue: Deque[TranscodeTask] = deque()
        self.running_tasks: List[TranscodeTask] = []
        self.completed_tasks: List[TranscodeTask] = []
        self.failed_tasks: List[TranscodeTask] = []
        self.max_concurrent_tasks = max_concurrent_tasks
        self._lock = asyncio.Lock()
    
    async def add_task(self, task: TranscodeTask) -> bool:
        """添加任务到队列"""
        async with self._lock:
            self.pending_queue.append(task)
            return True
    
    async def get_next_task(self) -> Optional[TranscodeTask]:
        """获取下一个可执行任务"""
        async with self._lock:
            if len(self.running_tasks) >= self.max_concurrent_tasks:
                return None
            
            if self.pending_queue:
                task = self.pending_queue.popleft()
                self.running_tasks.append(task)
                return task
            
            return None
    
    async def complete_task(self, task: TranscodeTask) -> None:
        """标记任务完成"""
        async with self._lock:
            if task in self.running_tasks:
                self.running_tasks.remove(task)
                self.completed_tasks.append(task)
    
    async def fail_task(self, task: TranscodeTask, error_message: str) -> None:
        """标记任务失败"""
        async with self._lock:
            if task in self.running_tasks:
                self.running_tasks.remove(task)
                task.fail(error_message)
                self.failed_tasks.append(task)
    
    async def pause_task(self, task: TranscodeTask) -> bool:
        """暂停任务"""
        async with self._lock:
            if task in self.running_tasks:
                task.pause()
                return True
            return False
    
    async def resume_task(self, task: TranscodeTask) -> bool:
        """恢复任务"""
        async with self._lock:
            if task in self.running_tasks and task.status == TaskStatus.PAUSED:
                task.resume()
                return True
            return False
    
    async def cancel_task(self, task: TranscodeTask) -> bool:
        """取消任务"""
        async with self._lock:
            if task in self.running_tasks:
                task.cancel()
                self.running_tasks.remove(task)
                return True
            elif task in self.pending_queue:
                self.pending_queue.remove(task)
                task.cancel()
                return True
            return False
    
    def get_queue_stats(self) -> Dict[str, Any]:
        """获取队列统计信息"""
        return {
            "pending": len(self.pending_queue),
            "running": len(self.running_tasks),
            "completed": len(self.completed_tasks),
            "failed": len(self.failed_tasks),
            "max_concurrent": self.max_concurrent_tasks,
            "total_tasks": len(self.pending_queue) + len(self.running_tasks) + 
                          len(self.completed_tasks) + len(self.failed_tasks),
        }
    
    def get_all_tasks(self) -> List[TranscodeTask]:
        """获取所有任务"""
        return (list(self.pending_queue) + 
                self.running_tasks + 
                self.completed_tasks + 
                self.failed_tasks)
    
    def get_task_by_id(self, task_id: str) -> Optional[TranscodeTask]:
        """根据ID获取任务"""
        all_tasks = self.get_all_tasks()
        for task in all_tasks:
            if task.task_id == task_id:
                return task
        return None
    
    def clear_completed(self) -> None:
        """清空已完成任务"""
        self.completed_tasks.clear()
        self.failed_tasks.clear()
    
    def get_progress_summary(self) -> Dict[str, Any]:
        """获取进度摘要"""
        total_tasks = self.get_queue_stats()["total_tasks"]
        completed_tasks = len(self.completed_tasks)
        
        if total_tasks > 0:
            overall_progress = (completed_tasks / total_tasks) * 100
        else:
            overall_progress = 0
        
        # 计算运行中任务的平均进度
        running_progress = 0
        if self.running_tasks:
            running_progress = sum(task.progress for task in self.running_tasks) / len(self.running_tasks)
        
        return {
            "overall_progress": overall_progress,
            "running_progress": running_progress,
            "completed_count": completed_tasks,
            "failed_count": len(self.failed_tasks),
            "total_count": total_tasks,
        }